import io
import os
import uuid
import wave
import time
import numpy
import pyaudio
import AudioConfig
from pydub import playback
from pydub import AudioSegment
from aip import AipSpeech

x
aipSpeech = AipSpeech(AudioConfig.BAIDU_AIP_APP_ID, AudioConfig.BAIDU_AIP_API_KEY, AudioConfig.BAIDU_AIP_SECRET_KEY)


# 检查说话
def checkSay(data, rate=0.1):
    count = 0
    wave_data = list(numpy.fromstring(data, dtype=numpy.byte))
    for i in range(len(wave_data)):
        if wave_data[i] >= 50:
            count += 1
    return count / len(data) >= rate

    # 开始录音


def recordAudio(num=3):
    p = pyaudio.PyAudio()
    # 创建音频流
    stream = p.open(format=pyaudio.paInt16,  # 音频编码方式
                    channels=1,  # 单声道
                    rate=16000,  # 采样率
                    input=True,
                    frames_per_buffer=1024)
    # print("Start Recording...")
    frames = []  # 录制的音频流

    count = 0
    data = stream.read(1024)
    if not checkSay(data):
        return -1

    AudioConfig.set_state(False)

    while True:
        data = stream.read(1024)
        if checkSay(data):
            frames.append(data)
            count = 0
        else:
            time.sleep(0.1)
            data = stream.read(1024)
            if checkSay(data):
                frames.append(data)
                count = 0
            else:
                count += 1
                if count >= num:
                    break

    # 录制完成
    stream.stop_stream()
    stream.close()
    p.terminate()

    # 保存音频文件
    wf = wave.open(os.path.join(AudioConfig.BASE_PATH, 'w.wav'), 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
    wf.setframerate(16000)
    wf.writeframes(b''.join(frames))
    wf.close()


# 说话
def say(str, spd=5):
    result = aipSpeech.synthesis(str, 'zh', 4, {
        'vol': 8,
        'spd': spd,
        'pit': 9,
    })

    song = AudioSegment.from_mp3(io.BytesIO(result))
    playback.play(song)


# 识别语音
def recognizeSound():
    dict = {"cuid": str(uuid.uuid1()), "dev_pid": 1537}
    with open(os.path.join(AudioConfig.BASE_PATH, 'w.wav'), 'rb') as f:
        file = f.read()
    result = aipSpeech.asr(file, 'wav', 16000, dict)

    if result["err_no"] == 0:
        return result["result"][0]
    else:
        return result
